package com.frog.rss;

import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import android.util.Log;

import com.frog.rss.domain.RSSItem;

public class RSSHelper {

	public static List<RSSItem> loadRssItems(URL url) {
		List<RSSItem> rssItems = new ArrayList<RSSItem>();
		try {
			XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
			factory.setNamespaceAware(true); // 设置为true，则factory创建的XmlPullParser提供对xml
												// 命名空间的支持
			XmlPullParser parser = factory.newPullParser();
			parser.setInput(url.openStream(), null);
			int eventType = parser.getEventType();
			String title = "";
			String link = "";
			String description = "";
			String pubDate = "";
			while (eventType != XmlPullParser.END_DOCUMENT) {
				if (eventType == XmlPullParser.START_TAG) {
					String tagName = parser.getName();
					if (tagName.equals("item")) {
						title = link = description = pubDate = "";
					} else if (tagName.equals("title")) {
						parser.next();
						title = parser.getText();
					} else if (tagName.equals("link")) {
						parser.next();
						link = parser.getText();
					} else if (tagName.equals("description")) {
						parser.next();
						description = parser.getText();
					} else if (tagName.equals("pubDate")) {
						parser.next();
						pubDate = parser.getText();
					}
				} else if (eventType == XmlPullParser.END_TAG) {
					// We have a comlete item -- post it back to the UI
					// using the mHandler (necessary because we are not
					// running on the UI thread).
					String tag = parser.getName();
					if (tag.equals("item")) {
						RSSItem item = new RSSItem(title, link, pubDate,
								description, null, RSSItem.UNSTARRED_STATUS,
								RSSItem.UNREAD_STATUS);
						// mHandler.post(new ItemAdder(item));
						rssItems.add(item);
					}
				}
				eventType = parser.next();
			}
		} catch (Exception e) {
			Log.e(RSSHelper.class.getName(), e.getMessage());
		}
		return rssItems;
	}

	public static List<Map<String, String>> rssItemsToListMap(
			List<RSSItem> rssItems) {
		return rssItemsToListMap(rssItems, 50);
	}

	public static List<Map<String, String>> rssItemsToListMap(
			List<RSSItem> rssItems, int charSize) {
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		for (RSSItem each : rssItems) {
			Map<String, String> eachMap = new HashMap<String, String>();
			eachMap.put(RSSItem.TITLE, each.getTitle());
			eachMap.put(RSSItem.DESCRIPTION,
					each.getDescription().substring(0, charSize));
			eachMap.put(RSSItem.PUBDATE, each.getPubDate());
			list.add(eachMap);
		}
		return list;
	}
}
